<template>
  <v-app id="inspire">
  <v-content>
    <v-container >
  <v-card
    class="overflow-hidden"
    color=" lighten-1"
  >
    <v-toolbar
      flat
      color="blue"
    >
      <v-icon>mdi-account</v-icon>
      <v-toolbar-title class="font-weight-light">{{this.$route.params.id}}</v-toolbar-title>

      <v-spacer></v-spacer>
      <v-btn
        color="blue darken-3"
        fab
        small
        @click="isEditing = !isEditing"
      >
        <v-icon v-if="isEditing">mdi-close</v-icon>
        <v-icon v-else>mdi-pencil</v-icon>
      </v-btn>
    </v-toolbar>
    <v-card-text>

      <v-form v-model="valid"
              ref="form"
      >
        <v-container>
          <v-text-field
            :disabled="!isEditing"
            v-model="MyFileTitle"
            :rules="titleRule"
            label="Title"
          ></v-text-field>
          <v-text-field
            :disabled="!isEditing"
            label="Abstract"
            :rules="titleRule"
            v-model="MyFileAbstract"
          ></v-text-field>
          <v-combobox
            v-model="team"
            :items="users"
            :disabled="!isEditing"
            outlined
            chips
            small-chips
            label="Team"
            multiple
          ></v-combobox>

          <v-row>
            <v-col>

              <span>拖拽确定作者顺序</span>

              <draggable
                v-model="team"
                @change="change"
                @start="start"
                @end="end"
                :move="move">
                <li v-for="(item, index) in team" :key="index">
                  第{{index+1}}作者：{{item}}</li>
              </draggable>
            </v-col>
          </v-row>

          <v-row
            v-for="(author, index) in team"
            :key="author"
          >
            <v-col
              cols="12"
              md="3"
            >
              <v-text-field
                v-model="team[index]"
                :key="team[index]"
                disabled
                :rules="titleRule"
                label="Name"
                required
              ></v-text-field>
            </v-col>

            <v-col
              cols="12"
              md="3"
            >
              <v-text-field
                v-model="affiliations[index]"
                :disabled="!isEditing"
                :rules="titleRule"
                label="Affiliation"
                required
              ></v-text-field>

            </v-col>
            <v-col
              cols="12"
              md="3"
            >
              <v-text-field
                v-model="regions[index]"
                :disabled="!isEditing"
                :rules="titleRule"
                label="Region"
                required
              ></v-text-field>
            </v-col>
            <v-col
              cols="12"
              md="3"
            >
              <v-text-field
                v-model="emails[index]"
                :disabled="!isEditing"
                :rules="emailRule"
                label="E-mail"
                required
              ></v-text-field>
            </v-col>
          </v-row>
        </v-container>
      </v-form>
      <v-file-input accept=".pdf" label="File input"
                    :disabled="!isEditing"
      ></v-file-input>
      <span class="subheading">Select Topic</span>
      <v-chip-group
        v-model="selection"
        :items="topics"
        active-class="blue--text text--accent-4"
        mandatory
        multiple
      >
        <v-chip v-for="topic in topics" :key="topic"
                :disabled="!isEditing"
        >{{topic}}</v-chip>
      </v-chip-group>
    </v-card-text>
    <v-divider></v-divider>
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn
        :disabled="!isEditing"
        color="success"
        @click="save"
      >
        Save
      </v-btn>
    </v-card-actions>
    <v-snackbar
      v-model="hasSaved"
    >{{text}}
      <v-btn
        color="pink"
        text
        @click="closeSnackbar"
      >
        Close
      </v-btn>
    </v-snackbar>
  </v-card>
      <side-bar></side-bar>
    </v-container>
  </v-content>
  </v-app>
</template>

<script>
import draggable from 'vuedraggable'
import SideBar from './Components/SideBar'
import axios from 'axios'
import store from '../store'
export default {
  name: 'MyContribution',
  props: {
    source: String
  },
  data () {
    const generateMeetingTopics = _ => {
      const topics = []
      this.$axios.post('/getMeetingTopics', this.$route.params.id)
        .then(resp => {
          var response = resp.data
          response.forEach((topic, index) => {
            topics.push(topic)
          })
        })
      return topics
    }
    const generateFileTitle = _ => {
      this.$axios.post('/getPaperInfo',
        {
          contributor: store.state.userName,
          fileTitle: this.$route.query.fileTitle})
        .then(resp => {
          console.log(resp.data)
          var response = resp.data
          this.team = response.authorNames
          this.MyFileTitle = response.fileTitle
          this.MyFileAbstract = response.fileAbstract
          this.id = response.id
        })
        .catch(error => {
          console.log(error)
        })
      return this.MyFileTitle
    }
    return {
      valid: true,
      // nameRules: [
      //   v => !!v || 'Abbr Name is required',
      //   v => v.length <= 10 || 'Must be less than 10 characters',
      // ],
      // emailRules: [
      //   v => !!v || 'E-mail is required',
      //   v => /.+@.+/.test(v) || 'E-mail must be valid',
      // ],
      hasSaved: false,
      isEditing: null,
      model: null,
      meetingName: this.$route.params.id,
      MyFileTitle: generateFileTitle(),
      originalFileTitle: this.$route.query.fileTitle,
      MyFileAbstract: '',
      users: [],
      team: [],
      selection: [],
      selectedTopics: [],
      topics: generateMeetingTopics(),
      affiliations: [],
      regions: [],
      emails: [],
      id: '',
      text: '',
      titleRule: [
        v => !!v || 'Required'
      ],
      emailRule: [
        v => !!v || 'E-mail is required',
        v => /.+@.+/.test(v) || 'E-mail must be valid'
      ],
      dragging: false
    }
  },

  methods: {
    customFilter (item, queryText, itemText) {
      const textOne = item.name.toLowerCase()
      const textTwo = item.abbr.toLowerCase()
      const searchText = queryText.toLowerCase()

      return textOne.indexOf(searchText) > -1 ||
          textTwo.indexOf(searchText) > -1

      },
    closeSnackbar(){
      this.hasSaved = false
      this.$router.push('/myContribution')
    },
      save () {
        if (this.$refs.form.validate()) {
          if (this.selection.length === 0) {
            console.log("no topic")
            this.text = '未选择topic'
            this.hasSaved = true
          } else if (this.team.length === 0) {
            this.text = '未选择author'
            this.hasSaved = true
          } else if (document.querySelector('input[type=file]').files.length===0){
            this.text = '请选择文件!'
            this.hasSaved = true
          } else {
            const meetingTopics = this.topics;
            this.selection.forEach((topicIndex, index) => {
              this.selectedTopics[index] = meetingTopics[topicIndex]
            })
            // var formData = new FormData() // 声明一个FormData对象
            var formData = new window.FormData() // vue 中使用 window.FormData(),否则会报 'FormData isn't definded'
            this.isEditing = !this.isEditing
            this.hasSaved = true
            formData.set('file', document.querySelector('input[type=file]').files[0]) // 'file' 这个名字要和后台获取文件的名字一样;
            formData.set('user', store.state.userName)
            formData.set('meeting', this.meetingName)
            formData.set('originalFileTitle', this.originalFileTitle)
            formData.set('newFileTitle', this.MyFileTitle)
            formData.set('fileAbstract', this.MyFileAbstract)
            formData.set('topics', this.selectedTopics)
            formData.set('authorNames', this.team)
            formData.set('authorAffiliations', this.affiliations)
            formData.set('authorRegions', this.regions)
            formData.set('authorEmails', this.emails)
            formData.set('id', this.id)

          console.log('file:' + document.querySelector('input[type=file]').files[0].name)
          console.log('user:' + store.state.userName)
          console.log('MyFileTitle:' + this.MyFileTitle)
          console.log('originalFileTitle:' + this.originalFileTitle)
          console.log('abstract:' + this.MyFileAbstract)

          axios({
            url: '/updateWork',
            data: formData,
            method: 'post',
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then((res) => {
            console.log(res.data)
            this.text = 'success'
            this.hasSaved = true
            // alert('Success')
            // this.$router.push('/myContribution')
          })
            .catch(error => {
              console.log(error)
              this.text = 'Fail to upload'
              this.hasSaved = true
              // alert('Fail to upload')
            })
        }
      }
    },
    change (evt) {
      console.log(evt)
    },
    // start ,end ,add,update, sort, remove 得到的都差不多
    start (evt) {
      console.log(evt)
    },
    end (evt) {
      // console.log(evt)
      // evt.item // 可以知道拖动的本身
      // evt.to // 可以知道拖动的目标列表
      // evt.from // 可以知道之前的列表
      // evt.oldIndex // 可以知道拖动前的位置
      // evt.newIndex // 可以知道拖动后的位置
    },
    move (evt, originalEvent) {
      console.log(evt)
      console.log(originalEvent) // 鼠标位置
    },
    removeAt (idx) {
      this.list.splice(idx, 1)
    },
    add: function () {
      id++
      this.list.push({ name: 'Juan ' + id, id, text: '' })
    }
  },
  components: {
    SideBar,
    draggable
  }
}
</script>
